package project.weather.weather;
/*
 * 待完成：用MVC模式分开DB和Action操作
 * 增删改查看导印统功能的实现
 */

import jxl.write.WriteException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONException;
import org.json.JSONObject;
import project.weather.dao.WeatherData;
import project.weather.dao.MyExcel;
import project.weather.dao.WeatherDocumentDao;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ServletAction extends HttpServlet {
    String module="weather";
    String sub="information";
    public void showDebug(String msg){
        System.out.println("["+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())+"]["+module+"/"+sub+"/ServletAction]"+msg);
    }
    /*
     * 处理顺序：先是service，后根据情况doGet或者doPost
     */
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        processAction(request,response);
    }
    /*========================================函数分流 开始========================================*/
    public void processAction(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        boolean actionOk = false;
        int resultCode=0;
        String resultMsg="ok";
        JSONObject json=new JSONObject();
        showDebug("processAction收到的action是："+action);
        if (action == null){
            resultMsg="传递过来的action是NULL";
        }else{
            //这几个常规增删改查功能
            if (action.equals("get_weather_information_record")) {
                actionOk=true;
                try {
                    getWeatherRecord(request, response, json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (action.equals("insert_weather_information_to_DB")) {
                actionOk=true;
                try {
                    addWeatherInfRecord(request, response, json);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (action.equals("modify_Weather_record")) {
                actionOk=true;
                try {
                    modifyWeatherRecord(request, response, json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (action.equals("delete_Weather_record")) {
                actionOk=true;
                try {
                    deleteWeatherRecord(request, response, json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (action.equals("export_Weather_Information_record")) {
                actionOk=true;
                try {
                    exportWeatherRecord(request, response, json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (action.equals("query_file_information_record")) {
                actionOk=true;
                try {
                    QueryWeatherRecord(request, response, json);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                responseBack(request,response,json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    /*========================================函数分流 结束========================================*/
    /*========================================公共函数 开始========================================*/
    private WeatherData getPageParameters(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException {
        WeatherData data=new WeatherData();
        HttpSession session = request.getSession();
        /*----------------------------------------获取所有表单信息 开始----------------------------------------*/
        showDebug("[getPageParameters]----------------------------------------获取所有表单信息 开始----------------------------------------");
        JSONObject param=data.getParam();
        Enumeration requestNames=request.getParameterNames();
        for(Enumeration e=requestNames;e.hasMoreElements();){
            String thisName=e.nextElement().toString();
            String thisValue=request.getParameter(thisName);
            showDebug("[getPageParameters]"+thisName+"="+thisValue);
            showDebug(data.getParam().toString());
            param.put(thisName, thisValue);
        }
        String[] ids=request.getParameterValues("ids[]");if(ids!=null){param.put("ids[]",ids);}			//后头用这样来取出：String[] ids=(String[])(data.getParam().get("ids[]"));
        showDebug("[getPageParameters]----------------------------------------获取所有表单信息 完毕----------------------------------------");
        /*----------------------------------------获取所有表单信息 完毕----------------------------------------*/
        return data;
    }
    private void responseBack(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException {
        boolean isAjax=true;if (request.getHeader("x-requested-with") == null || request.getHeader("x-requested-with").equals("com.tencent.mm")){isAjax=false;}	//判断是异步请求还是同步请求，腾讯的特殊
        if(isAjax){
            response.setContentType("application/json; charset=UTF-8");
            try {
                response.getWriter().print(json);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            String action=json.getString("action");
            String errorNo="0";
            String errorMsg="ok";
            String url = module+"/"+sub+"/result.jsp?action="+action+"&result_code="+errorNo+ "&result_msg=" + errorMsg;
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*========================================公共函数 结束========================================*/
    /*========================================CRUD业务函数 开始========================================*/

    private void getWeatherRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.getWeatherRecord(data,json);
    }
    private void modifyWeatherRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException, UnsupportedEncodingException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.modifyWeatherRecord(data,json);
    }
    private void deleteWeatherRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException, UnsupportedEncodingException {
        WeatherDocumentDao dao = new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.deleteWeatherRecord(data, json);
    }
    private void addWeatherInfRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.addWeatherInfRecord(data,json);
    }
    /*========================================CRUD业务函数 结束========================================*/
    private void QueryWeatherRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.getWeatherRecord(data,json);
    }


    private void exportWeatherRecord(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException, IOException, WriteException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.getWeatherRecord(data,json);
        getExportWeatherRecordToFile(json,data);
        getExportWeatherRecordToExcel(json,data);
        getExportWeatherRecordToPDF(json,data);
        getExportWeatherRecordToTxt(json,data);
    }

    private void getExportWeatherRecordToTxt(JSONObject json, WeatherData data) {

    }

    private void getExportWeatherRecordToPDF(JSONObject json, WeatherData data) {

    }

    private void getExportWeatherRecordToExcel(JSONObject json, WeatherData data) throws WriteException, IOException, JSONException {
        //获取当前文件的绝对路径
        String rootPath = this.getServletContext().getRealPath("/");
        String savePath="/file/";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newWeatherName = df.format(new Date()) + "_" + "export_excel_weather_information.xls";
        // 创建自定义的excel
        MyExcel excel=new MyExcel(rootPath+savePath+newWeatherName);
        json.put("download_url","../"+savePath+newWeatherName);
        json.put("file_path",savePath+newWeatherName);
        excel.exportData(data,json);
    }

    private void getExportWeatherRecordToFile(JSONObject json, WeatherData data) throws JSONException {
        // Map数据转化为Json，再转换为String
        String jsonStr = json.toString();
        //获取当前文件的绝对路径
        String rootPath = this.getServletContext().getRealPath("/");
        String savePath="/file/";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + "export_Weather_Information.txt";
        File jsonFile = new File(rootPath+savePath,newFileName);
        // 注意：一下的download_url后的字符串前必须带有“/”，否则就是在本地寻找那个路径，会发现找不到这个项目文件
        json.put("download_url",savePath+newFileName);
        try {
            // 文件不存在就创建文件
            if (!jsonFile.exists()) {
                jsonFile.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(jsonFile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(jsonStr);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getWeatherInfBySomeType(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws JSONException, SQLException {
        WeatherDocumentDao dao=new WeatherDocumentDao();
        WeatherData data=getPageParameters(request,response,json);
        dao.getWeatherInfBySomeType(data,json);

    }
}

